#include "Application.h"
#include "AStar.h"
#include <fstream>
#include <iostream>
#include <windows.h>
#include <list>

Application::Application()
: m_star(NULL)
{
	m_map = new char*[MAP_HEIGHT];

	for (unsigned int i = 0; i < MAP_WIDTH; ++i)
	{
		m_map[i] = new char[MAP_WIDTH];
	}

	m_star = new AStar(*this);
}

Application::~Application()
{
	for (unsigned int i = 0; i < MAP_WIDTH; ++i)
	{
		delete [] m_map[i];
	}

	delete [] m_map;
}

void Application::LoadMap(const std::string _filename)
{
	std::ifstream stream(_filename.c_str());

	for (unsigned int i = 0; i < MAP_HEIGHT; ++i)
	{
		stream.read(m_map[i], MAP_WIDTH);
		stream.ignore(); // Ignore la fin de la ligne

		std::string temp = m_map[i];
		size_t pos = temp.find('S');

		if (std::string::npos != pos)
		{
			m_start.first = pos;
			m_start.second = i;
		}

		pos = temp.find('E');

		if (std::string::npos != pos)
		{
			m_end.first = pos;
			m_end.second = i;
		}
	}

	stream.close();
	m_star->SetGoal(m_end);
	m_star->SetMap(m_map);
}

void Application::ShowMap()
{
	system("cls");

	for (unsigned int i = 0; i < MAP_HEIGHT; ++i)
	{
		char temp[33];
		memcpy(temp, m_map[i], MAP_WIDTH);
		temp[MAP_WIDTH] = '\0';
		std::cout << temp << std::endl;
	}
}

void Application::ShowPath()
{
	for (unsigned int i = 0; i < Application::MAP_HEIGHT; ++i)
	{
		for (unsigned int j = 0; j < Application::MAP_WIDTH; ++j)
		{
			if (m_map[i][j] == '.')
			{
				m_map[i][j] = ' ';
			}
		}
	}

	const std::list<std::pair<unsigned int, unsigned int>> path = m_star->GetPath();
	std::list<std::pair<unsigned int, unsigned int>>::const_iterator it = path.begin();

	for (; it != path.end(); ++it)
	{
		m_map[it->second][it->first] = '.';
	}
}

void Application::ReadKeyboard()
{
	if (::GetAsyncKeyState(VK_LEFT))
	{
		if (m_start.first > 0 && m_map[m_start.second][m_start.first-1] != '1')
		{
			m_map[m_start.second][m_start.first] = ' ';
			--m_start.first;
			m_map[m_start.second][m_start.first] = 'S';
		}
	}

	if (::GetAsyncKeyState(VK_RIGHT))
	{
		if (m_start.first < MAP_WIDTH && m_map[m_start.second][m_start.first+1] != '1')
		{
			m_map[m_start.second][m_start.first] = ' ';
			++m_start.first;
			m_map[m_start.second][m_start.first] = 'S';
		}
	}

	if (::GetAsyncKeyState(VK_UP))
	{
		if (m_start.second > 0 && m_map[m_start.second-1][m_start.first] != '1')
		{
			m_map[m_start.second][m_start.first] = ' ';
			--m_start.second;
			m_map[m_start.second][m_start.first] = 'S';
		}
	}

	if (::GetAsyncKeyState(VK_DOWN))
	{
		if (m_start.second < MAP_HEIGHT && m_map[m_start.second+1][m_start.first] != '1')
		{
			m_map[m_start.second][m_start.first] = ' ';
			++m_start.second;
			m_map[m_start.second][m_start.first] = 'S';
			//m_star->FindPath(m_start);
		}
	}

	m_map[m_end.second][m_end.first] = 'E';

	m_star->FindPath(m_start);
}